package common.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import staticclass.CommonConfig;

public class MyExcelHandle {

	/**
	 * 根据表头，数据生成excel文件
	 * 
	 * @param list
	 *            表格数据（包含表头）
	 * @param cw
	 *            列宽，默认200
	 * @param filePathName
	 *            输出文件名
	 * @return 文件Url
	 */
	public static String export(List<String[]> list, int[] cw,
			String filePathName) {
		// 创建表格
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("表名");
		HSSFCellStyle style_title = wb.createCellStyle();
		style_title.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
		HSSFFont font = wb.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style_title.setFont(font);
		HSSFCellStyle style_content = wb.createCellStyle();
		style_content.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
		HSSFRow row;
		HSSFCell cell;
		String[] ss;
		int cw_len = 0;
		if (null != cw)
			cw_len = cw.length;
		for (int i = 0, ilen = list.size(); i < ilen; i++) {
			row = sheet.createRow(i);
			ss = list.get(i);
			for (int j = 0, jlen = ss.length; j < jlen; j++) {
				cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(ss[j]);
				if (i == 0) {
					cell.setCellStyle(style_title);
					if (cw_len > j)
						sheet.setColumnWidth(j, cw[i]);
					else
						sheet.setColumnWidth(j, 200 * 36);
				} else {
					cell.setCellStyle(style_content);
				}
			}
		}
		// 输出
		String realPath = ServletActionContext.getServletContext().getRealPath(
				"")
				+ "/assets/excel/";
		// String serverUrl = CommonConfig.domainName +
		// ServletActionContext.getRequest().getContextPath() + "/assets/excel/"
		// + filePathName;
		String serverUrl = CommonConfig.domainName
				+ ServletActionContext.getRequest().getContextPath()
				+ "/assets/excel/" + filePathName;
		File file = new File(realPath);
		if (!file.exists())
			file.mkdirs();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(realPath + filePathName);
			wb.write(fos);
		} catch (Exception e) {
		} finally {
			if (null != fos)
				try {
					fos.close();
				} catch (Exception e2) {
				}
		}
		return serverUrl;
	}

	public static String objToStr(Object obj) {
		if (null != obj)
			return String.valueOf(obj);
		else
			return "";
	}

}
